package com.wanli.agent.dialog;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.wanli.agent.R;
import com.wanli.agent.base.DataCallBack;
import com.wanli.agent.bean.BankCardBean;
import com.wanli.agent.bean.BaseResponseBean;
import com.wanli.agent.bean.ImageBean;
import com.wanli.agent.event.ALiDiscernEvent;
import com.wanli.agent.homepage.StoreInfoFragment;
import com.wanli.agent.homepage.model.HomePageModelImpl;
import com.wanli.agent.homepage.model.IHomePageModel;
import com.wanli.agent.utils.Base64BitmapUtil;
import com.wanli.agent.utils.GlideEngine;
import com.wanli.agent.utils.PermissionsManager;
import com.wanli.agent.utils.SPManager;
import com.wanli.agent.utils.SPUtils;
import com.wanli.agent.utils.ToastUtil;
import com.wanli.agent.widget.ViewLoading;

import org.greenrobot.eventbus.EventBus;

import java.text.BreakIterator;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.app.Activity.RESULT_OK;

/**
 * Author:HWC
 */
public class UpdateSettlementDialog extends DialogFragment {
    @BindView(R.id.tv_settle_name)
    EditText tvSettleName;
    @BindView(R.id.tv_settle_mobile)
    EditText tvSettleMobile;
    @BindView(R.id.tv_id_card)
    EditText tvIdCard;
    @BindView(R.id.tv_card_no)
    EditText tvCardNo;
    @BindView(R.id.tv_card_name)
    TextView tv_card_name;
    @BindView(R.id.tv_bank_city)
    TextView tv_bank_city;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.ll_card_name)
    LinearLayout ll_card_name;
    @BindView(R.id.tv_settlement_account_type)
    TextView tv_settlement_account_type;
    @BindView(R.id.ll_settlement_account_type)
    LinearLayout ll_settlement_account_type;
    @BindView(R.id.iv_bank_card_scan)
    ImageView iv_bank_card_scan;
    @BindView(R.id.iv_id_card_scan)
    ImageView iv_id_card_scan;
    private Dialog dialog;
    private OnCallBackListener onCallBackListener;
    private Activity mActivity;
    private String settle_name;
    private String settle_mobile;
    private String id_card;
    private String card_no;
    private String bank_name;
    private String bank_type;
    private String bank_city;
    private ArrayList<String> options4Items = new ArrayList<>();
    private String settle_type;
    private String[] permissions;
    private int openType;//0 相册，1相机
    private BottomSheetDialog idDialog;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initWindow();
        View view = inflater.inflate(R.layout.dialog_updata_settlement, null);
        ButterKnife.bind(this, view);
        mActivity = getActivity();

        initView();
        options4Items.add("对公账户");
        options4Items.add("对私账户");
        return view;
    }

    public static UpdateSettlementDialog newInstance(String settle_name, String settle_mobile, String id_card, String card_no, String bank_name, String bank_city, String settle_type) {
        Bundle args = new Bundle();
        UpdateSettlementDialog fragment = new UpdateSettlementDialog();
        args.putString("settle_name", settle_name);
        args.putString("settle_mobile", settle_mobile);
        args.putString("id_card", id_card);
        args.putString("card_no", card_no);
        args.putString("bank_name", bank_name);
        args.putString("bank_city", bank_city);
        args.putString("settle_type", settle_type);
        fragment.setArguments(args);
        return fragment;
    }

    public void setOnCallBackListener(OnCallBackListener onCallBackListener) {
        this.onCallBackListener = onCallBackListener;
    }

    //    初始化请求
    private void initView() {
        permissionsManager = new PermissionsManager(getActivity());

        settle_name = getArguments().getString("settle_name");
        settle_mobile = getArguments().getString("settle_mobile");
        id_card = getArguments().getString("id_card");
        card_no = getArguments().getString("card_no");
        bank_name = getArguments().getString("bank_name");
        bank_type = getArguments().getString("bank_type");
        bank_city = getArguments().getString("bank_city");
        settle_type = getArguments().getString("settle_type");

        tvSettleName.setText(settle_name);
        tvSettleMobile.setText(settle_mobile);
        tvIdCard.setText(id_card);
        tv_card_name.setText(bank_name);
        tv_bank_city.setText(bank_city);
        tvCardNo.setText(card_no);

        if ("corporate".equals(settle_type)) {
            tv_settlement_account_type.setText("对公账户");
        } else if ("personal".equals(settle_type)) {
            tv_settlement_account_type.setText("对私账户");
        }


        ll_card_name.setOnClickListener(v -> {
            BankDepositDialog dialog = BankDepositDialog.newInstance("0");

            dialog.show(getChildFragmentManager(), "dialog");

            dialog.setOnCallBackListener((branch_province, branch_city, open_acc_area, bank_name, banktype, open_acc_bank_name, open_acc_bank_type) -> {

                String provinceName = branch_province;
                String cityName = branch_city;
                String areaName = open_acc_area;

                String bankName = bank_name;
                bank_type = banktype;

                tv_card_name.setText(bankName);
                tv_bank_city.setText(cityName);


            });
        });
        ll_settlement_account_type.setOnClickListener(v -> {

            showPickerView();
        });


        iv_bank_card_scan.setOnClickListener(v -> {
            //1银行卡
            SPUtils.put(SPManager.Key.DOCUMENT_TYPE, "1");
            showPictureSelectorDialog();
        });
        iv_id_card_scan.setOnClickListener(v -> {
            //2身份证 正面
            SPUtils.put(SPManager.Key.DOCUMENT_TYPE, "2");
            idDialog();

        });
    }

    //设置window属性
    private void initWindow() {
        //去掉dialog的标题
        dialog = this.getDialog();
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setCancelable(true);
        Window window = dialog.getWindow();
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        window.getAttributes().windowAnimations = R.style.commomDialog;
        window.setAttributes(lp);
        window.setBackgroundDrawable(new ColorDrawable());
    }


    private void showPictureSelectorDialog() {

        selectPicDialog = new BottomSheetDialog(mActivity, R.style.Dialog);
        selectPicDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_bottom_select_pictrue, null);
        // 相册
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 相机
        TextView camera = view.findViewById(R.id.tv_select_pictrue_camera);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> handlerPhotoAlbumClick());
        camera.setOnClickListener(v -> handlerCameraClick());
        cancel.setOnClickListener(v -> cancelPictureDialog());

        selectPicDialog.setContentView(view);
        selectPicDialog.show();
    }

    /**
     * 打开相机
     */
    private void openCamera() {
        PictureSelector.create(getActivity())
                .openCamera(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
        cancelPictureDialog();

    }

    /**
     * 点击相机
     */
    private void handlerCameraClick() {
        openType = 1;
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.CAMERA};

        if (PermissionsManager.checkPermissions(permissions)) {
            openCamera();
            cancelPictureDialog();
            return;
        }

        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openCamera();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    /**
     * 打开相册
     */
    private void openPhotoAlbum() {
        PictureSelector.create(getActivity())//
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)//
                .maxSelectNum(1)//
                .minSelectNum(1)//
                .compress(true)//
                .selectionMedia(mediaList)//
                .cropCompressQuality(30)// 裁剪压缩质量 默认90 int
                .minimumCompressSize(100)// 小于20kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 点击相册
     */
    private void handlerPhotoAlbumClick() {
        openType = 0;
        cancelPictureDialog();
        permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, //
                Manifest.permission.READ_EXTERNAL_STORAGE};

        if (PermissionsManager.checkPermissions(permissions)) {
            openPhotoAlbum();
            cancelPictureDialog();
            return;
        }
        permissionsManager.requestPermissionsEach(permissions);
        permissionsManager.setResultListener((allGranted, rejectPermissionList) -> {
            if (allGranted) {
                openPhotoAlbum();
                cancelPictureDialog();
            } else {
                permissionsManager.showDialog();
            }
        });
    }

    private BottomSheetDialog selectPicDialog;
    private PermissionsManager permissionsManager;
    private List<LocalMedia> mediaList = new ArrayList<>();

    private void cancelPictureDialog() {
        if (selectPicDialog != null) {
            selectPicDialog.cancel();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @OnClick(R.id.tv_commit)
    public void onViewClicked() {
        String settleName = tvSettleName.getText().toString();
        String settleMobile = tvSettleMobile.getText().toString();
        String idCard = tvIdCard.getText().toString();
        String cardNo = tvCardNo.getText().toString();
        String bank_name = tv_card_name.getText().toString();
        String bank_city = tv_bank_city.getText().toString();
        String settlement_account_type = tv_settlement_account_type.getText().toString();

        if (TextUtils.isEmpty(settleName)) {
            ToastUtil.showShort("请输入姓名");
            return;
        }
        if (TextUtils.isEmpty(settleMobile)) {
            ToastUtil.showShort("请输入手机号");
            return;
        }
        if (TextUtils.isEmpty(idCard)) {
            ToastUtil.showShort("请输入身份证号");
            return;
        }
        if (TextUtils.isEmpty(cardNo)) {
            ToastUtil.showShort("请输入结算银行卡号");
            return;
        }
        if (TextUtils.isEmpty(bank_name)) {
            ToastUtil.showShort("请选择结算银行卡名称");
            return;
        }
        if (TextUtils.isEmpty(bank_type)) {
            ToastUtil.showShort("请重新选择结算开户行所在市");
            return;
        }
        if (TextUtils.isEmpty(settlement_account_type)) {
            ToastUtil.showShort("请选择结算账户类型");
            return;
        }


        String settle_type = "";
        if ("对公账户".equals(settlement_account_type)) {
            settle_type = "corporate";
        } else if ("对私账户".equals(settlement_account_type)) {
            settle_type = "personal";
        }


        ViewLoading.showProgress(mActivity);

        new HomePageModelImpl().requestVerifyBankFourFactor(settleName, settleMobile, idCard, cardNo, bank_name, bank_type, bank_city, settle_type, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                onCallBackListener.onCallBack(settleName, settleMobile, idCard, cardNo, bank_name, bank_type, bank_city);
                dismiss();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public interface OnCallBackListener {
        void onCallBack(String settleName, String settleMobile, String idCard, String cardNo, String bank_name, String bankType, String tv_bank_city);
    }

    private void showPickerView() {
        // 弹出选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {

                tv_settlement_account_type.setText(options4Items.get(options1));

            }
        }).setTitleText("")
                .setTitleSize(16)
                .setSubmitColor(getResources().getColor(R.color.text_color_2))//确定按钮文字颜色
                .setSubCalSize(14)
                .setCancelColor(getResources().getColor(R.color.text_color_2))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(R.color.line_color_gray))
                .setTextColorCenter(getResources().getColor(R.color.text_color_2))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2)
                .isDialog(true)
                .build();

        pvOptions.setPicker(options4Items);


        Dialog mDialog = pvOptions.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvOptions.getDialogContainerLayout().setLayoutParams(params);

            Window window = mDialog.getWindow();
            if (window != null) {
                window.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.BOTTOM;
            }
        }
        pvOptions.show();

    }

    public void get(String card_num) {
        tvCardNo.setText(card_num);
    }
    public void getId(String name,String id) {
        tvSettleName.setText(name);
        tvIdCard.setText(id);
    }

    public boolean isDestroy() {
        boolean isDestroy = false;
        if (mActivity == null || mActivity.isFinishing()) {
            isDestroy = true;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (mActivity.isDestroyed()) {
                isDestroy = true;
            }
        }
        return isDestroy;
    }
    private void idDialog() {
        idDialog = new BottomSheetDialog(mActivity, R.style.Dialog);
        idDialog.getWindow().getAttributes().windowAnimations = R.style.commomDialog;
        View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_id_select_pictrue_zhengmian, null);
        // 头像面
        TextView album = view.findViewById(R.id.tv_select_pictrue_album);
        // 取消
        TextView cancel = view.findViewById(R.id.tv_select_pictrue_cancel);

        album.setOnClickListener(v -> clickFront());
        cancel.setOnClickListener(v -> cancelidDialog());

        idDialog.setContentView(view);
        idDialog.show();
    }
    /**
     * 点击正面
     */
    private void clickFront() {
        idDialog.dismiss();
        showPictureSelectorDialog();
    }
    private void cancelidDialog() {
        if (idDialog != null) {
            idDialog.cancel();
        }
    }

}
